<template>
    <view>
        <TopNavigation title="规则列表" backText="房间列表" :titleSub='"房间:" + roomName' />
        <view class="view-container">
            <!-- <view class="view-container-left">
                <view class="view-container-left-top" @click="goToCreateRoom">
                    添加规则
                </view>
            </view> -->
            <view class="view-container-right">
                <view class="view-container-right-add" @click="openAddRuleModal">

                    <text>添加规则</text>
                </view>
                <BoxView :titBoxObj="{
                    title: '规则列表',
                    titleCount: `共有${ruleList.length}个规则`
                }" padding="0" style="background: #FFFFF4;">
                    <view class="view-container-right-list">
                        <view class="view-container-right-list-item-empty"
                            v-if="ruleList.length === 0 && !isAddingNewRule && !loading">
                            <text>暂无规则</text>
                        </view>
                        <view class="view-container-right-list-item-empty" v-if="loading">
                            <text>加载中...</text>
                        </view>
                        <!-- 新增规则表单 -->
                        <view v-if="isAddingNewRule"
                            class="view-container-right-list-item view-container-right-list-add">
                            <view class="view-container-right-list-item-title">
                                <view class="next-row ">
                                    <view class="id-value" style="width: 50%;">
                                        <text class="form-label">起始点：</text>
                                        <input v-model="ruleForm.startPoint" placeholder="请输入起始点"
                                            class="form-input" />
                                    </view>
                                    <view class="id-text" style="width: 50%;">
                                        <text class="form-label">结束点：</text>
                                        <input v-model="ruleForm.endPoint" placeholder="请输入结束点" class="form-input" />
                                    </view>
                                </view>
                                <view class="next-row">
                                    <view class="id-text" style="width: 50%;">
                                        <text class="form-label">准备时间：</text>
                                        <input v-model="ruleForm.prepareTimeSeconds" placeholder="秒" type="number"
                                            class="form-input" />
                                    </view>
                                    <view class="id-text" style="width: 50%;">
                                        <text class="form-label">限制时间：</text>
                                        <input v-model="ruleForm.limitTimeSeconds" placeholder="秒" type="number"
                                            class="form-input" />
                                    </view>
                                </view>
                                <view class="next-row">
                                    <view class="id-text" style="width: 50%;">
                                        <text class="form-label">回合数：</text>
                                        <input v-model="ruleForm.round" placeholder="请输入回合数" type="number"
                                            class="form-input" />
                                    </view>
                                    <view class="id-text" style="width: 50%;">
                                        <text class="form-label">得分模式：</text>
                                        <picker mode="selector" :range="scoreModelOptions" style="width: 300rpx;"
                                            :value="ruleForm.scoreModel" @change="onScoreModelChange">
                                            <view class="form-picker">{{ scoreModelOptions[ruleForm.scoreModel] ||
                                                '请选择' }}</view>
                                        </picker>
                                    </view>
                                </view>
                                <view class="next-row">
                                    <view class="id-text" style="width: 50%;">
                                        <text class="form-label">对战模式：</text>
                                        <picker mode="selector" :range="battleModelOptions" style="width: 300rpx;"
                                            :value="ruleForm.battleModel" @change="onBattleModelChange">
                                            <view class="form-picker">{{ battleModelOptions[ruleForm.battleModel] ||
                                                '请选择' }}</view>
                                        </picker>
                                    </view>
                                    <view class="id-text" style="width: 50%;"></view>
                                </view>
                                <view class="next-button">
                                    <view class="next-button-item1" @click.stop="saveRule">提交</view>
                                    <view class="next-button-item2" @click.stop="cancelAddRule">取消</view>
                                </view>
                            </view>
                        </view>
                        <view v-if="!loading && ruleList.length > 0" class="view-container-right-list-item"
                            :class="{ 'view-container-right-list-item-editing': editingRuleId === rule.id }"
                            v-for="rule in ruleList" :key="rule.id">
                            <view class="view-container-right-list-item-title">
                                <!-- 编辑状态 -->
                                <template v-if="editingRuleId === rule.id">
                                    <view class="next-row">
                                        <view class="id-text"><text class="rule-id-disabled">规则ID：</text><text class="rule-id-disabled">{{ rule.id }}</text></view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-value" style="width: 50%;">
                                            <text class="form-label">起始点：</text>
                                            <input v-model="ruleForm.startPoint" placeholder="请输入起始点" class="form-input" />
                                        </view>
                                        <view class="id-text" style="width: 50%;">
                                            <text class="form-label">结束点：</text>
                                            <input v-model="ruleForm.endPoint" placeholder="请输入结束点" class="form-input" />
                                        </view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text" style="width: 50%;">
                                            <text class="form-label">准备时间：</text>
                                            <input v-model="ruleForm.prepareTimeSeconds" placeholder="秒" type="number" class="form-input" />
                                        </view>
                                        <view class="id-text" style="width: 50%;">
                                            <text class="form-label">限制时间：</text>
                                            <input v-model="ruleForm.limitTimeSeconds" placeholder="秒" type="number" class="form-input" />
                                        </view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text" style="width: 50%;">
                                            <text class="form-label">回合数：</text>
                                            <input v-model="ruleForm.round" placeholder="请输入回合数" type="number" class="form-input" />
                                        </view>
                                        <view class="id-text" style="width: 50%;">
                                            <text class="form-label">得分模式：</text>
                                            <picker mode="selector" :range="scoreModelOptions" style="width: 300rpx;"
                                                :value="ruleForm.scoreModel" @change="onScoreModelChange">
                                                <view class="form-picker">{{ scoreModelOptions[ruleForm.scoreModel] || '请选择' }}</view>
                                            </picker>
                                        </view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text" style="width: 50%;">
                                            <text class="form-label">对战模式：</text>
                                            <picker mode="selector" :range="battleModelOptions" style="width: 300rpx;"
                                                :value="ruleForm.battleModel" @change="onBattleModelChange">
                                                <view class="form-picker">{{ battleModelOptions[ruleForm.battleModel] || '请选择' }}</view>
                                            </picker>
                                        </view>
                                        <view class="id-text" style="width: 50%;"></view>
                                    </view>
                                    <view class="next-button">
                                        <view class="next-button-item1" @click.stop="saveRule">保存</view>
                                        <view class="next-button-item2" @click.stop="cancelEditRule">取消</view>
                                    </view>
                                </template>
                                <!-- 查看状态 -->
                                <template v-else>
                                    <view class="next-row">
                                        <view class="id-text"><text>规则ID：</text>{{ rule.id }}</view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-value"><text>起始点：</text>{{ rule.startPoint || '未设置' }}</view>
                                        <view class="id-text"><text>结束点：</text>{{ rule.endPoint || '未设置' }}</view>
                                    </view>
 
                                    <view class="next-row">
                                        <view class="id-text"><text>准备时间：</text>{{ formatTime(rule.prepareTime) }}</view>
                                        <view class="id-text"><text>限制时间：</text>{{ formatTime(rule.limitTime) }}</view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text"><text>回合数：</text>{{ rule.round || '未设置' }}</view>
                                        <view class="id-text"><text>得分模式：</text>{{ getScoreModelText(rule.scoreModel) }}
                                        </view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text"><text>对战模式：</text>{{ getBattleModelText(rule.battleModel) }}
                                        </view>
                                        <view class="id-text"><text>创建时间：</text>{{ formatDate(rule.createTime) }}</view>
                                    </view>
                                    <view class="next-button">
                                        <view class="next-button-item1" @click.stop="editRule(rule)">编辑</view>
                                        <view class="next-button-item2" @click.stop="deleteRule(rule)">删除</view>
                                    </view>
                                </template>
                            </view>
                        </view>
                    </view>

                </BoxView>
            </view>
        </view>
    </view>

</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { MatchRoomRuleAPI } from '@/api/battle.js'
import BoxView from "@/components/UiView/BoxView.vue";
import TopNavigation from "@/components/UiView/TopNavigation.vue";

const loading = ref(false)
const ruleList = ref([])
const roomId = ref('')
const roomName = ref('')

// 规则表单相关数据
const showRuleFormModal = ref(false)
const submitting = ref(false)
const isEditingRule = ref(false)
const currentRule = ref(null)
const editingRuleId = ref(null) // 正在编辑的规则ID

// 新增规则相关
const isAddingNewRule = ref(false)

// 选择器相关数据
const showScoreModelPicker = ref(false)
const showBattleModelPicker = ref(false)

// 规则表单数据
const ruleForm = ref({
    startPoint: '',
    endPoint: '',
    prepareTimeSeconds: '',
    limitTimeSeconds: '',
    round: '',
    scoreModel: 0,
    battleModel: 0
})

const scoreModelIndex = ref(0)
const battleModelIndex = ref(0)

// 得分模式映射
const scoreModelMap = {
    0: '不记分',
    1: '时间短',
    2: '时间长',
    3: '距离短',
    4: '距离长',
    5: '得分少',
    6: '得分多',
    7: '步数短',
    8: '步数长'
}

// 对战模式映射
const battleModelMap = {
    0: '接力',
    1: '单回合',
    2: '多回合'
}

const scoreModelOptions = [
    '不记分',
    '时间短',
    '时间长',
    '距离短',
    '距离长',
    '得分少',
    '得分多',
    '步数短',
    '步数长'
]

const battleModelOptions = [
    '接力',
    '单回合',
    '多回合'
]

const getScoreModelText = (scoreModel) => scoreModelMap[scoreModel] || '未知'
const getBattleModelText = (battleModel) => battleModelMap[battleModel] || '未知'

const formatDate = (timestamp) => {
    if (!timestamp) return '未设置'
    const date = new Date(timestamp)
    return date.toLocaleString('zh-CN')
}

const formatTime = (milliseconds) => {
    if (!milliseconds) return '未设置'
    const seconds = Math.floor(milliseconds / 1000)
    return `${seconds}秒`
}

const fetchRuleList = async () => {
    if (!roomId.value) return;
    loading.value = true
    try {
        const result = await MatchRoomRuleAPI.page({
            matchRoomId: roomId.value,
            pageNum: 0,
            pageSize: 100
        })
        console.log('规则查询API返回结果:', result)
        if (result.code === 0) {
            ruleList.value = result.data?.list || result.data || []
        } else {
            ruleList.value = []
            throw new Error(result.msg || '获取规则失败')
        }
    } catch (error) {
        console.error('获取规则失败:', error)
        uni.showToast({
            title: error.message || '获取规则失败',
            icon: 'none'
        })
    } finally {
        loading.value = false
    }
}

onLoad((options) => {
    if (options.roomId) {
        roomId.value = options.roomId
        roomName.value = decodeURIComponent(options.roomName || '')
        fetchRuleList()
    }
})

// 打开添加规则表单
const openAddRuleModal = () => {
    isAddingNewRule.value = true
    resetRuleForm()
}

// 取消添加规则
const cancelAddRule = () => {
    isAddingNewRule.value = false
}


// 打开编辑规则
const editRule = (rule) => {
    editingRuleId.value = rule.id
    currentRule.value = rule
    fillRuleForm(rule)
    isEditingRule.value = true
}

// 取消编辑规则
const cancelEditRule = () => {
    editingRuleId.value = null
    currentRule.value = null
    isEditingRule.value = false
    resetRuleForm()
}

// 得分模式选择变化
const onScoreModelChange = (e) => {
    ruleForm.value.scoreModel = e.detail.value
}

// 对战模式选择变化
const onBattleModelChange = (e) => {
    ruleForm.value.battleModel = e.detail.value
}


// 重置规则表单
const resetRuleForm = () => {
    ruleForm.value = {
        startPoint: '',
        endPoint: '',
        prepareTimeSeconds: '',
        limitTimeSeconds: '',
        round: '',
        scoreModel: 0,
        battleModel: 0
    }
    scoreModelIndex.value = 0
    battleModelIndex.value = 0
}

// 填充规则表单
const fillRuleForm = (rule) => {
    ruleForm.value = {
        startPoint: rule.startPoint || '',
        endPoint: rule.endPoint || '',
        prepareTimeSeconds: rule.prepareTime ? Math.floor(rule.prepareTime / 1000) : '',
        limitTimeSeconds: rule.limitTime ? Math.floor(rule.limitTime / 1000) : '',
        round: rule.round || '',
        scoreModel: rule.scoreModel || 0,
        battleModel: rule.battleModel || 0
    }
    scoreModelIndex.value = rule.scoreModel || 0
    battleModelIndex.value = rule.battleModel || 0
}

// 打开得分模式选择模态框
const openScoreModelPicker = () => {
    showScoreModelPicker.value = true
}

// 打开对战模式选择模态框
const openBattleModelPicker = () => {
    showBattleModelPicker.value = true
}

// 关闭得分模式选择模态框
const closeScoreModelPicker = () => {
    showScoreModelPicker.value = false
}

// 关闭对战模式选择模态框
const closeBattleModelPicker = () => {
    showBattleModelPicker.value = false
}

// 保存规则
const saveRule = async () => {
    if (!ruleForm.value.startPoint.trim()) {
        uni.showToast({
            title: '请输入起始点',
            icon: 'none'
        })
        return
    }

    if (!ruleForm.value.endPoint.trim()) {
        uni.showToast({
            title: '请输入结束点',
            icon: 'none'
        })
        return
    }

    submitting.value = true
    try {
        const data = {
            matchRoomId: roomId.value,
            startPoint: ruleForm.value.startPoint,
            endPoint: ruleForm.value.endPoint,
            prepareTime: ruleForm.value.prepareTimeSeconds ? parseInt(ruleForm.value.prepareTimeSeconds) * 1000 : 0,
            limitTime: ruleForm.value.limitTimeSeconds ? parseInt(ruleForm.value.limitTimeSeconds) * 1000 : 0,
            round: ruleForm.value.round ? parseInt(ruleForm.value.round) : 1,
            scoreModel: ruleForm.value.scoreModel,
            battleModel: ruleForm.value.battleModel
        }

        let result
        if (isEditingRule.value && currentRule.value) {
            result = await MatchRoomRuleAPI.edit({
                ...data,
                matchRoomRuleId: currentRule.value.id
            })
        } else {
            result = await MatchRoomRuleAPI.create(data)
        }

        if (result.code === 0) {
            uni.showToast({
                title: isEditingRule.value ? '更新成功' : '创建成功',
                icon: 'success'
            })
            
            // 清除编辑状态
            isAddingNewRule.value = false
            editingRuleId.value = null
            isEditingRule.value = false
            currentRule.value = null
            resetRuleForm()
            
            fetchRuleList()
        } else {
            throw new Error(result.msg || (isEditingRule.value ? '更新失败' : '创建失败'))
        }
    } catch (error) {
        console.error('保存规则失败:', error)
        uni.showToast({
            title: error.message || '保存失败',
            icon: 'none'
        })
    } finally {
        submitting.value = false
    }
}

// 删除规则
const deleteRule = (rule) => {
    uni.showModal({
        title: '确认删除',
        content: `确定要删除规则 "${rule.startPoint} -> ${rule.endPoint}" 吗？`,
        success: async (res) => {
            if (res.confirm) {
                try {
                    const result = await MatchRoomRuleAPI.remove({
                        matchRoomRuleId: rule.id
                    })

                    if (result.code === 0) {
                        uni.showToast({
                            title: '删除成功',
                            icon: 'success'
                        })
                        fetchRuleList()
                    } else {
                        throw new Error(result.msg || '删除失败')
                    }
                } catch (error) {
                    console.error('删除规则失败:', error)
                    uni.showToast({
                        title: error.message || '删除失败',
                        icon: 'none'
                    })
                }
            }
        }
    })
}

// 选择得分模式
const selectScoreModel = (index) => {
    scoreModelIndex.value = index
    ruleForm.value.scoreModel = index
    closeScoreModelPicker()
}

// 选择对战模式
const selectBattleModel = (index) => {
    battleModelIndex.value = index
    ruleForm.value.battleModel = index
    closeBattleModelPicker()
}
</script>
<style lang="scss" scoped>
.view-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: calc(100vh - 65rpx);
    padding: 0 20rpx;
    overflow: hidden;


    .form-label {
        font-size: 12rpx;
        color: #333;
    }
    
    .rule-id-disabled {
        color: #999 !important;
        font-size: 14rpx;
    }

    &-right {
        flex: 1;
        height: 100%;
        overflow: hidden;
        position: relative;

        &-add {
            z-index: 1000;
            position: absolute;
            color: #fff;
            top: 8rpx;
            left: 10rpx;
            font-size: 12rpx;
            border-bottom: 1rpx solid #eeeeee;

        }

        &-list {
            padding: 10rpx;
            overflow: auto;
            height: calc(100% - 60rpx);

            &-add {
                background: #FFF9E6;
            }
            
            &-item-editing {
                background: #FFF9E6;
                border: 2rpx solid #3D85EC;
            }

            &-item {
                background: #F0F0E4;
                border-radius: 10rpx;
                padding: 10rpx;
                margin-bottom: 10rpx;
                font-size: 14rpx;

                &-empty {
                    text-align: center;
                    margin-top: 80rpx;
                }


                .next-button {
                    display: flex;
                    justify-content: end;
                    align-items: center;
                    margin-top: 10rpx;

                    &-item1,
                    &-item2 {
                        width: 108rpx;
                        height: 30rpx;
                        font-size: 14rpx;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        padding-bottom: 4rpx;
                        color: #fff;
                    }


                    &-item1 {
                        background: url('/static/buttons/button2-1.png') no-repeat center center;
                        background-size: 100% 100%;
                        margin-right: 10rpx;
                    }

                    &-item2 {
                        background: url('/static/buttons/button7.png') no-repeat center center;
                        background-size: 100% 100%;
                    }
                }

                .next-row {
                    display: flex;
                    //   justify-content: space-between;
                    align-items: center;
                    margin-top: 10rpx;

                    view {
                        width: 50%;
                        display: flex;
                        align-items: center;
                    }

                    text {
                        display: inline-block;
                        font-size: 14rpx;
                        color: #99A1A4;
                        width: 70rpx;
                        text-align: right;
                        flex-shrink: 0;
                    }
                }

                .form-input {
                    flex: 1;
                    height: 30rpx;
                    padding: 0 5rpx;
                    background: #fff;
                    border-radius: 4rpx;
                    font-size: 12rpx;
                    margin-left: 10rpx;
                    margin-right: 20rpx;
                    box-sizing: border-box;
                }

                .form-picker {
                    flex: 1;
                    min-height: 30rpx;
                    padding: 0 5rpx;
                    background: #fff;
                    border-radius: 4rpx;
                    font-size: 12rpx;
                    margin-left: 10rpx;
                    display: flex;
                    align-items: center;
                    color: #333;
                    box-sizing: border-box;
                }
            }
        }
    }

}
</style>